import { ExceptionFilter, HttpException, Catch } from "@nestjs/common";
import { ArgumentsHost } from "@nestjs/common"
import { Response, Request } from 'express'

/**
 * 异常过滤器作用域有: 方法范围, 控制器范围, 全局范围
 * https://docs.nestjs.cn/9/exceptionfilters
 */
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        // throw new Error("Method not implemented.");
        const ctx = host.switchToHttp()
        const response = ctx.getResponse<Response>()
        const request = ctx.getRequest<Request>()
        const status = exception.getStatus()
        // const re:string = exception.getResponse()

        response.status(status)
        .json({
            code: status,
            // message: re.error,
            timestamp: new Date().toISOString(),
            path: request.url
        })
    }
    
}